let currentLogs = [];
let stackTraceModal;

document.addEventListener('DOMContentLoaded', function() {
    stackTraceModal = new bootstrap.Modal(document.getElementById('stackTraceModal'));
    loadTags();
    filterLogs();
    // 每30秒自动刷新一次
    setInterval(filterLogs, 30000);
});

let tagDescriptions = {};

function loadTags() {
    fetch('/api/config')
        .then(response => response.json())
        .then(config => {
            const tagSet = new Set();
            // 构建标签到描述的映射
            Object.values(config.apis).forEach(category => {
                tagSet.add(category.tag);
                if (!tagDescriptions[category.tag]) {
                    tagDescriptions[category.tag] = category.description;
                }
            });
            
            const tagFilter = document.getElementById('tagFilter');
            tagFilter.innerHTML = '<option value="">全部</option>';
            Array.from(tagSet).sort().forEach(tag => {
                tagFilter.innerHTML += `<option value="${tag}">${tagDescriptions[tag] || tag}</option>`;
            });
        })
        .catch(error => console.error('Error loading tags:', error));
}

function filterLogs() {
    const packageFilter = document.getElementById('packageFilter').value;
    const tagFilter = document.getElementById('tagFilter').value;
    const methodFilter = document.getElementById('methodFilter').value;

    let url = '/api/logs';
    const params = new URLSearchParams();
    if (packageFilter) params.append('appPackage', packageFilter);
    if (tagFilter) params.append('tag', tagFilter);
    if (methodFilter) params.append('method', methodFilter);

    if (params.toString()) {
        url += '?' + params.toString();
    }

    fetch(url)
        .then(response => response.json())
        .then(logs => {
            currentLogs = logs;
            renderLogs(logs);
        })
        .catch(error => console.error('Error:', error));
}

function renderLogs(logs) {
    const tbody = document.getElementById('logsBody');
    tbody.innerHTML = '';

    logs.forEach(log => {
        const row = document.createElement('tr');
        const time = new Date(log.timestamp);
        row.innerHTML = `
            <td>${time.toLocaleString()}</td>
            <td>${log.appPackage}</td>
            <td>${tagDescriptions[log.tag] || log.tag || 'N/A'}</td>
            <td>${log.methodName}</td>
            <td>${log.deviceInfo}</td>
            <td>
                <button class="btn btn-sm btn-info" onclick='showStackTrace(${JSON.stringify(log.stackTrace)})'>
                    <i class="bi bi-list-columns"></i> 调用栈
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function showStackTrace(stackTrace) {
    document.getElementById('stackTraceContent').textContent = stackTrace;
    stackTraceModal.show();
}

function exportLogs() {
    if (currentLogs.length === 0) {
        alert('没有可导出的数据');
        return;
    }

    const workbook = XLSX.utils.book_new();
    const data = [
        ['时间', '应用包名', 'API类型', '方法名', '设备信息', '请求IP', '调用栈']
    ];

    currentLogs.forEach(log => {
        data.push([
            new Date(log.timestamp).toLocaleString(),
            log.appPackage,
            log.tag || 'N/A',
            log.methodName,
            log.deviceInfo,
            log.requestIp,
            log.stackTrace
        ]);
    });

    const worksheet = XLSX.utils.aoa_to_sheet(data);

    // 设置列宽
    const wscols = [
        {wch: 20}, // 时间
        {wch: 30}, // 应用包名
        {wch: 15}, // API类型
        {wch: 40}, // 方法名
        {wch: 30}, // 设备信息
        {wch: 15}, // 请求IP
        {wch: 50}  // 调用栈
    ];
    worksheet['!cols'] = wscols;

    XLSX.utils.book_append_sheet(workbook, worksheet, "隐私API调用日志");
    
    const fileName = `privacy_logs_${new Date().toISOString().split('T')[0]}.xlsx`;
    XLSX.writeFile(workbook, fileName);
}
